var util = require('util');
var EventEmitter = require('events').EventEmitter;

import { config } from "./modules/config";
import { logger } from './modules/logger';
var cloud = require('./modules/services/cloud-service');
var sync = require('./modules/services/sync-service');

var SyncServer = function () {
    EventEmitter.call(this);
    this.started = false;
}

util.inherits(SyncServer, EventEmitter);

SyncServer.prototype.timeDiff = function () {
    var currtime = new Date().getTime()
    return cloud.timestamp().catch(function () {
        return currtime;
    }).then(function (timestamp) {
        return currtime - timestamp;
    });
};

SyncServer.prototype.start = function () {
    Contract.expect(!this.started);

    function syncHandle() {
        if (cloud.heartbeat.online) {
            return sync.uploadResources()
                .then(sync.downloadUpdates)
                .then(sync.downloadResources)
                .then(sync.pendingCheck).catch(function (err) {
                    logger.error(err);
                    logger.error(err.stack);
                });
        }
        return Promise.resolve();
    }

    function scheduleSyncHandle() {
        setTimeout(function () {
            syncHandle().finally(function () {
                scheduleSyncHandle();
            });
        }, 5000);
    }

    var delayPromise = Promise.resolve(0);
    if (config.options.option && config.options.option.mode == 'open') {
        delayPromise = this.timeDiff().then(function (diff) {
            return diff < 0 ? -1 * diff : 0
        });
    }

    var self = this;
    delayPromise.then(function (delay) {
        setTimeout(function () {
            syncHandle().finally(function () {
                scheduleSyncHandle();
            });
            self.started = true;
        }, delay);
    });
    this.emit('ready', true);
}

var syncServer = new SyncServer();
cloud.startHeartbeat();
cloud.heartbeat.on('ready', function () {
    if (!syncServer.started) {
        syncServer.start();
    }
});

module.exports = syncServer;
